package com.example.buy.controller.api;

import com.example.buy.VO.UserVO;
import com.example.buy.base.controller.BaseApiController;
import com.example.buy.base.result.Result;
import com.example.buy.base.result.ResultCode;
import com.example.buy.model.User;
import com.example.buy.service.UserService;
import com.example.buy.util.MD5Util;
import com.example.buy.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@RestController
public class LoginApiController extends BaseApiController {
    @Autowired
    UserService userService;
//@Valid 用于验证注解是否符合要求，直接加在变量user之前，在变量中添加验证信息的要求
    @RequestMapping(value="/login")
    public Result<Object> login(@ModelAttribute(value="user") @Valid User user, BindingResult bindingResult,HttpServletResponse response){
        System.out.println(user);
        if(bindingResult.hasErrors()) {//后端验证是否为空
            return Result.failure();
        }
        UserVO dbUser = userService.getUser(user.getUsername());
        if(dbUser != null){//如果查询到该用户
            if(dbUser.getPassword().equals(MD5Util.inputToDb(user.getPassword(), dbUser.getDbflag()))){
                String token = UUIDUtil.getUUID();//
                userService.saveUserToRedisByToken(dbUser, token);//该token保存redis中3600秒
                Cookie cookie = new Cookie("token", token);//该token保存在cookies中3600秒
                cookie.setMaxAge(3600);
                cookie.setPath("/");
                response.addCookie(cookie);
                return Result.success();	// Result.success(); 200, "success"
            }else{
                return Result.failure(ResultCode.USER_LOGIN_ERROR);
            }
        }else{
            return Result.failure(ResultCode.USER_LOGIN_ERROR);
        }

    }
}
